package com.dtagri.fjwlw.fragment;

import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;

import com.dtagri.fjwlw.AppContext;
import com.dtagri.fjwlw.adapter.HistoricalDataAdapter;
import com.dtagri.fjwlw.api.FJwlwApi;
import com.dtagri.fjwlw.base.BaseListFragment;
import com.dtagri.fjwlw.base.ListBaseAdapter;
import com.dtagri.fjwlw.base.TGson;
import com.dtagri.fjwlw.bean.TjData;
import com.dtagri.fjwlw.ui.HistoricalDataActivity;
import com.dtagri.fjwlw.util.StringUtils;
import com.google.gson.reflect.TypeToken;

/**
 * 历史数据
 * 
 * @author wxjn
 * 
 */
@SuppressLint("ValidFragment")
public class HistoricalDataFragment extends BaseListFragment<TjData> {

	private HistoricalDataAdapter historicalDataAdapter;
	private HistoricalDataActivity context2;

	public HistoricalDataFragment(Context context) {
		context2 = (HistoricalDataActivity) context;
	}

	public HistoricalDataFragment() {
	}

	@Override
	protected ListBaseAdapter<TjData> getListAdapter() {
		historicalDataAdapter = new HistoricalDataAdapter();
		return historicalDataAdapter;
	}

	@Override
	protected void sendRequestData() {
		Integer equipId = AppContext.curEquipment().getEquipId();
		Integer company_id = AppContext.user.getCompanyId();
		System.out.println("-----公司ID------"+AppContext.user.getCompanyId());
		if (equipId == null) {
			getActivity().finish();
		}
		Integer areaId = AppContext.curSmallArea().getAreaId();
		String from = context2.getFromYear() + "-"
				+ (context2.getFromMonth() + 1) + "-" + context2.getFromDay()
				+ " 00:00:00";
		String to = context2.getToYear() + "-" + (context2.getToMonth() + 1)
				+ "-" + context2.getToDay() + " 23:59:59";
		FJwlwApi.history(equipId, company_id + "", areaId, mCurrentPage, from,
				to, mHandler);
	}

	@Override
	protected String getCacheKeyPrefix() {
		Integer equipId = AppContext.curEquipment().getEquipId();
		Integer areaId = AppContext.curSmallArea().getAreaId();

		String from = context2.getFromYear() + "-"
				+ (context2.getFromMonth() + 1) + "-" + context2.getFromDay()
				+ " 00:00:00";
		String to = context2.getToYear() + "-" + (context2.getToMonth() + 1)
				+ "-" + context2.getToDay() + " 23:59:59";
		return "history" + equipId + areaId + mCurrentPage + from + to;
	}

	@Override
	protected List<TjData> parseList(InputStream is) throws Exception {
		Type type = new TypeToken<List<TjData>>() {
		}.getType();
		List<TjData> res = TGson.gson.fromJson(
				StringUtils.inputStream2String(is), type);
		return res;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected List<TjData> readList(Serializable seri) {
		return (List<TjData>) seri;
	}

	@Override
	protected void custom() {
		super.custom();
		String equipName = AppContext.curEquipment().getEquipName();
		historicalDataAdapter.setKey(equipName);
	}

}
